1508B - Almost Sorted - CodeForces Solution


binary search combinatorics constructive algorithms implementation *1800

Please click on ads to support us..

Python Code:

from heapq import heapify, heappop, heappush
from itertools import cycle
from math import sqrt,ceil
import os

import sys
from collections import defaultdict,deque
from io import BytesIO, IOBase
     
         
             
 
    
 
 
 
 
 
 
    
from collections import Counter
from functools import lru_cache
from collections import deque
def main():
    from heapq import heappush,heappop,heapify
   
                
    

        

            
        
        
                        
                
        
        
                            
        
                                                                
    
            import bisect,math
    class SortedList():
        BUCKET_RATIO = 50
        REBUILD_RATIO = 170
    
        def __init__(self,buckets):
            buckets = list(buckets)
            buckets = sorted(buckets)
            self._build(buckets)
    
        def __iter__(self):
            for i in self.buckets:
                for j in i: yield j
    
        def __reversed__(self):
            for i in reversed(self.buckets):
                for j in reversed(i): yield j
    
        def __len__(self):
            return self.size
    
        def __contains__(self,x):
            if self.size == 0: return False
            bucket = self._find_bucket(x)
            i = bisect.bisect_left(bucket,x)
            return i != len(bucket) and bucket[i] == x
    
        def __getitem__(self,x):
            if x < 0: x += self.size
            if x < 0: raise IndexError
            for i in self.buckets:
                if x < len(i): return i[x]
                x -= len(i)
            raise IndexError
    
        def _build(self,buckets=None):
            if buckets is None: buckets = list(self)
            self.size = len(buckets)
            bucket_size = int(math.ceil(math.sqrt(self.size/self.BUCKET_RATIO)))
            tmp = []
            for i in range(bucket_size):
                t = buckets[(self.size*i)//bucket_size:(self.size*(i+1))//bucket_size]
                tmp.append(t)
            self.buckets = tmp
    
        def _find_bucket(self,x):
            for i in self.buckets:
                if x <= i[-1]:
                    return i
            return i
    
        def add(self,x):
                        if self.size == 0:
                self.buckets = [[x]]
                self.size = 1
                return True
    
            bucket = self._find_bucket(x)
            bisect.insort(bucket,x)
            self.size += 1
            if len(bucket) > len(self.buckets) * self.REBUILD_RATIO:
                self._build()
            return True
    
        def remove(self,x):
                        if self.size == 0: return False
            bucket = self._find_bucket(x)
            i = bisect.bisect_left(bucket,x)
            if i == len(bucket) or bucket[i] != x: return False
            bucket.pop(i)
            self.size -= 1
            if len(bucket) == 0: self._build()
            return True
    
        def lt(self,x):
                        for i in reversed(self.buckets):
                if i[0] < x:
                    return i[bisect.bisect_left(i,x) - 1]
    
        def le(self,x):
                        for i in reversed(self.buckets):
                if i[0] <= x:
                    return i[bisect.bisect_right(i,x) - 1]
    
        def gt(self,x):
                        for i in self.buckets:
                if i[-1] > x:
                    return i[bisect.bisect_right(i,x)]
    
        def ge(self,x):
                        for i in self.buckets:
                if i[-1] >= x:
                    return i[bisect.bisect_left(i,x)]
        def index(self,x):
                        ans = 0
            for i in self.buckets:
                if i[-1] >= x:
                    return ans + bisect.bisect_left(i,x)
                ans += len(i)
            return ans
    
        def index_right(self,x):
                        ans = 0
            for i in self.buckets:
                if i[-1] > x:
                    return ans + bisect.bisect_right(i,x)
                ans += len(i)
            return ans

        for _ in range(int(input())):
        n,k=map(int,input().split())
        if (n<62 and k>(1<<(n-1))):
            print(-1)
        else :
            s=[]
            for i in range(n):
                s.append("0")
            k-=1
            for b in range(min(61,n-1)):
                if (k>>b)&1:
                    s[n-2-b]="1"
            curr=1
            sz=1
            ans=[]
            for i in range(n):
                if s[i]=="0":
                    for j in range(curr+sz-1,curr-1,-1):
                        ans.append(j)
                    curr+=sz
                    sz=1
                else :
                    sz+=1
            print(*ans)   
    
        
        

                    

    
                
            
        
                           
        
 
BUFSIZE = 8192
 
 
class FastIO(IOBase):
    newlines = 0
 
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None
 
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
 
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
 
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
 
 
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda: self.buffer.read().decode('ascii')
        self.readline = lambda: self.buffer.readline().decode('ascii')
 
 
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
 
 
 
if __name__ == '__main__':
    main()

C++ Code:

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void solve() {
    int n;
    ll k;
    cin >> n >> k;

    if(n < 62 && k > 1LL << (n - 1)) {
        cout << "-1\n";
        return;
    }

    string s;
    for(int i = 0; i < n; i++)
        s += '0';
    k--;
    for(ll b = 0; b < min(60LL, (ll)(n - 1)); b++) {
        if((k >> b) & 1)
            s[n - 2 - b] = '1';
    }
    int cur = 1, sz = 1;
    vector<int> ans;
    for(int i = 0; i < n; i++) {
        if(s[i] == '0') {
            for(int j = cur + sz - 1; j >= cur; j--)
                ans.push_back(j);
            cur += sz;
            sz = 1;
        }
        else
            sz++;
    }
    for(auto &x : ans)
        cout << x << " ";
    cout << '\n';
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    int t;
    cin >> t;
    while(t--)
        solve();
}


Comments

Submit
0 Comments
More Questions

996A - Hit the Lottery
MSNSADM1 Football
MATCHES Playing with Matches
HRDSEQ Hard Sequence
DRCHEF Doctor Chef
559. Maximum Depth of N-ary Tree
821. Shortest Distance to a Character
1441. Build an Array With Stack Operations
1356. Sort Integers by The Number of 1 Bits
922. Sort Array By Parity II
344. Reverse String
1047. Remove All Adjacent Duplicates In String
977. Squares of a Sorted Array
852. Peak Index in a Mountain Array
461. Hamming Distance
1748. Sum of Unique Elements
897. Increasing Order Search Tree
905. Sort Array By Parity
1351. Count Negative Numbers in a Sorted Matrix
617. Merge Two Binary Trees
1450. Number of Students Doing Homework at a Given Time
700. Search in a Binary Search Tree
590. N-ary Tree Postorder Traversal
589. N-ary Tree Preorder Traversal
1299. Replace Elements with Greatest Element on Right Side
1768. Merge Strings Alternately
561. Array Partition I
1374. Generate a String With Characters That Have Odd Counts
1822. Sign of the Product of an Array
1464. Maximum Product of Two Elements in an Array